﻿using Flurl.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LocalNas.Application.Service.Wankeyun;
public class WankeyunApi : ISingleton
{
    private FlurlClient accountClient = new FlurlClient("https://account.onethingpcs.com");
    private CookieJar accountCookies = new CookieJar();
    public WankeyunApi()
    {
        accountClient.WithTimeout(10);    //10秒超时
    }

    public string GetRandomIP()
    {
        int iSeed = 10;
        Random ro = new Random(iSeed);
        long tick = DateTime.Now.Ticks;
        Random ran = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
        string ip = $"{ran.Next(1, 255)}.{ran.Next(1, 255)}.{ran.Next(0, 255)}.{ran.Next(0, 255)}";
        return ip;
    }

    public async Task InitLogin()
    {
        //accountClient
    }


    public string GetParams(Dictionary<string, string> logindata, bool isGet = false)
    {
        List<string> list = new List<string>();
        for (int i = 0; i < logindata.Count; i++)
        {
            var t = logindata.ElementAt(i);
            if (t.Key == "pwd")
            {
                list.Add(t.Key + "=" + UtilHelper.SignPassword(t.Value));
            }
            else
            {
                list.Add(t.Key + "=" + t.Value);
            }
        }
        list.Sort();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.Count; i++)
        {
            sb.Append(list[i]);
            if (i != list.Count - 1)
            {
                sb.Append("&");
            }
        }
        var gstr = sb.ToString();//如果get，不加key参数
        sb.Append("&");
        //var sessionid = GetCookie(client, apiAccountUrl, "sessionid");
        //sb.Append("key=").Append(sessionid);

        string str = sb.ToString();//这是sign的原文
        string sign = UtilHelper.GetMD5(str);//这是最终的sign
        return isGet ? $"{gstr}&sign={sign}" : $"{str}&sign={sign}";
    }
}
